package com.jyw.business.de.expand.task;

import cn.hutool.core.util.StrUtil;
import com.jyw.business.de.constant.TaskStateConstant;
import com.jyw.business.de.domain.DeTaskInfo;
import com.jyw.business.de.service.IDeTaskInfoService;
import com.jyw.business.de.service.ISysDemandReminderConfigService;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.vo.SysDemandReminderConfigVo;
import com.jyw.system.enums.MessageTypeEnum;
import com.jyw.system.service.ISysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 需求任务超时未完成提醒
 */
@Component("DeTaskCompletedTask")
@Slf4j
public class DeTaskCompletedTask {

    @Resource
    private IDeTaskInfoService taskInfoService;

    @Resource
    private ISysDemandReminderConfigService configService;

    @Resource
    private ISysMessageService messageService;

    @Resource
    private RedisCache redisCache;

    public void remind(){
        SysDemandReminderConfigVo config = configService.getDefaultConfig();
        //超时未分配开关
        if (config.getCompleteRemind()) {
            Date timeOut = DateUtils.addDays(DateUtils.getNowDate(), -config.getCompleteDay());
            List<DeTaskInfo> list = taskInfoService.lambdaQuery()
                    .in(DeTaskInfo::getTaskState, Arrays.asList(TaskStateConstant.PROCESSING,TaskStateConstant.PAUSE))
                    .ge(DeTaskInfo::getReqCompleteDate, timeOut)
                    .list();
            list.forEach(data->{
                if(!redisCache.hasKey(CacheConstants.DE_TASK_TIME_OUT_COMPLETED_KEY+data.getId())){
                    //通知处理人
                    messageService.sendSysMessage(
                            MessageTypeEnum.SYS_DEMAND.getValue(),
                            data.getTaskUser(),
                            StrUtil.format("您有一条任务【{}】，待完成，请尽快处理",data.getTaskName())
                    );
                    redisCache.setCacheObject(CacheConstants.DE_TASK_TIME_OUT_COMPLETED_KEY+data.getId(),data,config.getCompleteInterval(),TimeUnit.MINUTES);
                }
            });
        }
    }
}
